﻿using System;
using System.Collections.Generic;
using System.Text;
using TSVNAddin.SVN;

namespace TSVNAddin.Core
{
	public class WorkingRootFinder
	{
		private readonly SVNClientAdapter _SVNClientAdapter;

		public WorkingRootFinder(SVNClientAdapter svnClientAdapter)
		{
			_SVNClientAdapter = svnClientAdapter;
		}

		public string FindRoot(string path)
		{
			string directory = System.IO.Path.GetDirectoryName(path);
			
			for (;;)
			{
				SVNInfoArgs info = _SVNClientAdapter.GetInfo(directory + "\\");
				if (info != null)
					return BuildRoot(directory + "\\", info);

				int indexSeparetor = directory.LastIndexOf('\\');
				if (indexSeparetor == -1)
					return string.Empty;

				directory = directory.Remove(indexSeparetor);
			}
		}

		private string BuildRoot(string fileName, SVNInfoArgs info)
		{
			RootPathBuilder pathBuilder = new RootPathBuilder();
			return pathBuilder.BuildRoot(fileName, info.RepositoryRoot, info.Uri);
		}
	}
}
